package cn.springboot.pioneermall.chat.server;

import cn.springboot.pioneermall.chat.container.SessionContainer;
import cn.springboot.pioneermall.robotChat.domain.HsChatMessage;
import cn.springboot.pioneermall.robotChat.service.IHsChatMessageService;
import cn.springboot.pioneermall.util.SpringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.TimeZone;

@Component
@ServerEndpoint(value = "/websocket/chat/{userId}")
public class WebSocketServer {

    private static final IHsChatMessageService iHsChatMessageService =
            SpringUtils.getBean(IHsChatMessageService.class);

    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final Long KF_ID = 3099L;

    private static final String COMMON_HELLO_WORD = "抱歉,您的问题暂时无法回复,请点击【转人工】按钮进行转接";

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) throws Exception {
        SessionContainer.addSession(userId, session);
    }

    /**
     * 连接关闭时处理
     */
    @OnClose
    public void onClose(Session session, @PathParam("userId") String userId) throws IOException {
        if (session.isOpen()) {
            session.close();
        }
        SessionContainer.removeSession(userId);
    }

    /**
     * 抛出异常时处理
     */
    @OnError
    public void onError(Session session, @PathParam("userId") String userId, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        SessionContainer.removeSession(userId);
    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session, @PathParam("userId") String userId) throws IOException {
        //JSON
        objectMapper.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        HsChatMessage bean = objectMapper.readValue(message, HsChatMessage.class);
        iHsChatMessageService.insertHsChatMessage(bean);
        Long toUserId = bean.getToId();
        System.out.println(bean.getSendTime());
        Session targetSession = SessionContainer.getSessionById(String.valueOf(toUserId));
        if (targetSession != null) {
            targetSession.getBasicRemote().sendText(objectMapper.writeValueAsString(bean));
        }
    }

}
